<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="评价指标名称" prop="evaluationMetric">
        <el-select v-model="queryParams.evaluationMetric" placeholder="请选择评价指标名称" clearable>
          <el-option
            v-for="dict in initDicts"
            :key="dict.dictCode"
            :label="dict.dictLabel"
            :value="dict.dictCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权重值，例如 0.85" prop="weight">
        <el-input
          v-model="queryParams.weight"
          placeholder="请输入权重值，例如 0.85"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="queryParams.remarks"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:indicator:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:indicator:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:indicator:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:indicator:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="indicatorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="评价指标名称" align="center" prop="evaluationMetricName" />
      <el-table-column label="权重值，例如 0.85" align="center" prop="weight" />
      <el-table-column label="评估的具体规则或描述" align="center" prop="assessmentDetails" />
      <el-table-column label="评分的标准或方法" align="center" prop="scoringCriteria" />
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:indicator:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:indicator:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用于存储评价指标及其详细信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="评价指标名称" prop="evaluationMetric">
          <el-select v-model="form.evaluationMetric" placeholder="请选择评价指标名称"  @change="handleChangeIndexs">
            <el-option
              v-for="dict in initDicts"
              :key="dict.dictCode"
              :label="dict.dictLabel"
              :value="dict.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权重值，例如 0.85" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入权重值，例如 0.85" />
        </el-form-item>
        <el-form-item label="评估的具体规则或描述" prop="assessmentDetails">
          <el-input v-model="form.assessmentDetails" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="评分的标准或方法" prop="scoringCriteria">
          <el-input v-model="form.scoringCriteria" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listIndicator, getIndicator, delIndicator, addIndicator, updateIndicator } from "@/api/business/indicator";
import { getDicts,getData } from "@/api/system/dict/data";
import { getType} from "@/api/system/dict/type";

export default {
  name: "Indicator",
  data() {
    return {
      initDicts: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用于存储评价指标及其详细信息表格数据
      indicatorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        evaluationMetric: null,
        weight: null,
        assessmentDetails: null,
        scoringCriteria: null,
        createTime: null,
        remarks: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        evaluationMetric: [
          { required: true, message: "评价指标名称不能为空", trigger: "change" }
        ],
        weight: [
          { required: true, message: "权重值，例如 0.85不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getModInitDicts();
  },
  methods: {
    //获取默认字典
    getModInitDicts() {

      //improvement_will_type 或 job_performance_type
      getDicts("improvement_will_type").then(response => {

        console.log("datas....",response);
        this.initDicts = response.data;
      });
    },

    /** 查询用于存储评价指标及其详细信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listIndicator(this.queryParams).then(response => {
        this.indicatorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        evaluationMetric: null,
        weight: null,
        assessmentDetails: null,
        scoringCriteria: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remarks: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用于存储评价指标及其详细信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getIndicator(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用于存储评价指标及其详细信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateIndicator(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIndicator(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用于存储评价指标及其详细信息编号为"' + ids + '"的数据项？').then(function() {
        return delIndicator(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/indicator/export', {
        ...this.queryParams
      }, `indicator_${new Date().getTime()}.xlsx`)
    },
    handleChangeIndexs(value) {

      console.log("value ...is ",value);

      //获取本身
      this.getData(value).then(response => {
        let dictData = response.data;
        //权重
        this.form.weight = dictData.dictValue;

        console.log('Selected dictData ok metric:', dictData);

        this.getType(dictData.remark).then(response => {

          let childDictType = response.data;

          this.form.assessmentDetails = childDictType.remark;

          console.log('Selected dictData metric:', childDictType);

          this.getDicts(childDictType.dictType).then(response => {
            let dicts = response.data;

            let dataTemplate = childDictType.dataTemplate;

            // 提取 createBy 值
            const createByValues = dicts.map(item => item.dictValue);

            // 替换模板中的占位符
            let result = dataTemplate.replace(/\$\{(\d+)\}/g, (match, index) => {
              return createByValues[index - 1] || match; // 如果索引超出范围，保留原占位符
            });

            const weight = this.form.weight;

            result = result.replace(/\$\{weight\}/g, weight);

            console.log(result);
            this.form.scoringCriteria = result;

            console.log('Selected dicts metric:', dicts);
          });

        })

      });
    },

  }
};
</script>
